package com.alawn.framework.core.utils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.UnavailableSecurityManagerException;
import org.apache.shiro.session.InvalidSessionException;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;

import com.alawn.framework.services.security.User;
public class ShiroUtils {
	/**
	 * 获取授权主要对象
	 *
	 * @return Subject
	 */
	public static Subject getSubject() {
		return SecurityUtils.getSubject();
	}

	/**
	 * 获取当前登录用户
	 *
	 * @return User
	 */
	public static User getLoginUser() {
		try {
			Subject subject = SecurityUtils.getSubject();
			User principal = (User) subject.getPrincipal();
			if (principal != null) {
				return principal;
			}
			// subject.logout();
		} catch (UnavailableSecurityManagerException | InvalidSessionException ignored) {

		}
		return null;
	}

	/**
	 * 获取当前登陆名
	 *
	 * @return loginName
	 */
	public static String getLoginName() {
		User User = getLoginUser();
		if (User != null) {
			return User.getUsername();
		} else {
			return "";
		}
	}

	/**
	 * 获取当前会话
	 *
	 * @return Session
	 */
	public static Session getSession() {
		try {
			Subject subject = SecurityUtils.getSubject();
			Session session = subject.getSession(false);
			if (session == null) {
				session = subject.getSession();
			}
			if (session != null) {
				return session;
			}
			// subject.logout();
		} catch (InvalidSessionException ignored) {

		}
		return null;
	}
}
